<template>
  <div class="input-number-wrap">
    <u-input
      class="number-input"
      v-model="inputVal"
      type="digit"
      :height="height"
      :placeholder-style="placeholderStyle"
      :placeholder="placeholder"
      :clearable="clearable"
      @blur="blur"
    />
    <div class="unit" v-if="unit">{{ unit }}</div>
  </div>
  
</template>

<script>
  export default {
    props: {
      value: {
        type: [String, Number],
      },
      height: {
        type: [String, Number],
        default: 44,
      },
      min: {
        type: Number,
        default: 0,
      },
      max: {
        type: Number,
        default: 99999999,
      },
      precision: {
        type: Number,
        default: 2,
      },
      placeholder: {
        type: String,
        default: '请输入',
      },
      placeholderStyle: {
        type: String,
        default: 'color: #9ea5bb',
      },
      clearable: {
        type: Boolean,
        default: true,
      },
      unit: String,
    },
    data() {
      return {
        focus: false,
        inputVal: ''
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(val) {
          this.inputVal = this.verifyValue(val)
        }
      },
    },
    methods: {
      blur(value) {
        this.inputVal = this.verifyValue(value)
        this.$emit('input', this.inputVal)
      },
      verifyValue(value) {
        const { max, min, precision } = this.$props
        let newVal = Number(value)
        if (value == undefined || value == null || value === '' || Number.isNaN(newVal)) {
          return ''
        }
        newVal = this.toPrecision(newVal, precision)
        if (newVal > max || newVal < min) {
          newVal = newVal > max ? max : min
        }
        if ((newVal || newVal === 0) && this.precision > 0) {
          return (newVal = Number(newVal).toFixed(this.precision))
        }
        return newVal
      },
      toPrecision(num, pre) {
        if (pre === 0) return Math.round(num)
        let snum = String(num)
        const pointPos = snum.indexOf('.')
        if (pointPos === -1) return num
        const nums = snum.replace('.', '').split('')
        const datum = nums[pointPos + pre]
        if (!datum) return num
        const length = snum.length
        if (snum.charAt(length - 1) === '5') {
          snum = `${snum.slice(0, Math.max(0, length - 1))}6`
        }
        return Number.parseFloat(Number(snum).toFixed(pre))
      },
    },
  }
</script>

<style lang="less" scoped>
  .input-number-wrap {
    display: flex;
    .number-input {
      flex: 1;
    }
    .unit {
      flex-shrink: 0;
      font-size: 28rpx;
      color: #1A1A1A;
      margin-left: 12rpx;
      line-height: 44rpx;
    }
  }
</style>
